
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
const _ = cloud.database().command
export default async function (ctx: FunctionContext) {
  let body = ctx.body
  /**
   * {
   *     "name": "定时的",
   *     "inputType": 0,
   *     "selectList": "颠三倒四",
   *     "attrGroupId": "6561984bb5171888d9700a82"
   * }
   */
  if (nw.util.isNull(body.name)){
    return fail("平台属性名称不能为空")
  }
  if (nw.util.isNull(body.attrGroupId)){
    return  fail("平台分组不能为空")
  }
  if (nw.util.isNull(body.inputType)){
    body.sort = 0
  }
  if (nw.util.isNull(body.selectList)){
    body.remark = ""
  }
  //校验分组名称是否重复
  let count = await nw.db.count({
    dbName:"attr",
    whereJson:{deleted:0,name:_.eq(body.name),attrGroupId:_.eq(body.attrGroupId)}
  })
  if (count>0){
    return fail("属性名称重复")
  }
  //构建保存结果
  let data = {
    name:body.name,
    inputType:body.inputType,
    selectList:body.selectList,
    attrGroupId:body.attrGroupId,
    createTime:new Date(),
    updateTime:new Date(),
    deleted:0
  }

  let id = await nw.db.add({
    dbName:"attr",
    dataJson:data
  })
  if (nw.util.isNull(id)){
    return fail("保存失败")
  }
  return ok("保存成功")

}
